import { ref, computed } from "vue";
import { ElMessage } from "element-plus";
import { useSheddingStore } from "@/store/modules/hmi/shedding.store";
import { useErrorHandler } from "./useErrorHandler";
import { SheddingType } from "@/api/hmi/shedding.api";

/**
 * 稳控切负荷 Composable
 */
export function useShedding() {
  // Store
  const sheddingStore = useSheddingStore();

  // 错误处理
  const { handleError } = useErrorHandler();

  // 本地状态
  const localSheddingValue = ref<number>(0);
  const localRecoverValue = ref<number>(0);
  const refreshing = ref<boolean>(false);
  const updatingShedding = ref<boolean>(false);
  const updatingRecover = ref<boolean>(false);

  // 计算属性
  const isReady = computed(() => sheddingStore.isReady);
  const sheddingInfo = computed(() => sheddingStore.getCurrentSheddingInfo());
  const isLoading = computed(() => sheddingStore.isLoading || refreshing.value);
  const isUpdating = computed(
    () => sheddingStore.isUpdating || updatingShedding.value || updatingRecover.value
  );

  /**
   * 同步本地值
   */
  const syncLocalValues = () => {
    localSheddingValue.value = sheddingStore.getSheddingValue();
    localRecoverValue.value = sheddingStore.getRecoverValue();
  };

  /**
   * 刷新切负荷信息
   * @param cpu CPU 编号
   */
  const refreshSheddingInfo = async (cpu: number = 1) => {
    refreshing.value = true;

    try {
      await sheddingStore.fetchSheddingInfo(cpu);
      syncLocalValues();
      // ElMessage.success("稳控切负荷信息刷新成功");
    } catch (error: any) {
      handleError(error, "刷新稳控切负荷信息");
    } finally {
      refreshing.value = false;
    }
  };

  /**
   * 更新切负荷层级
   * @param cpu CPU 编号
   * @param value 层级值
   */
  const updateSheddingLevel = async (cpu: number = 1, value?: number) => {
    const valueToUpdate = value !== undefined ? value : localSheddingValue.value;

    // 验证数据
    const validation = sheddingStore.validateSheddingValue(valueToUpdate);
    if (!validation.isValid) {
      ElMessage.error(`数据验证失败：${validation.errors.join(", ")}`);
      return false;
    }

    updatingShedding.value = true;

    try {
      const result = await sheddingStore.updateSheddingLevel(
        cpu,
        SheddingType.SHEDDING,
        valueToUpdate
      );

      if (result.status) {
        ElMessage.success("切负荷层级更新成功");
        syncLocalValues();
        return true;
      } else {
        ElMessage.error("切负荷层级更新失败");
        return false;
      }
    } catch (error: any) {
      handleError(error, "更新切负荷层级");
      return false;
    } finally {
      updatingShedding.value = false;
    }
  };

  /**
   * 更新恢复负荷层级
   * @param cpu CPU 编号
   * @param value 层级值
   */
  const updateRecoverLevel = async (cpu: number = 1, value?: number) => {
    const valueToUpdate = value !== undefined ? value : localRecoverValue.value;

    // 验证数据
    const validation = sheddingStore.validateRecoverValue(valueToUpdate);
    if (!validation.isValid) {
      ElMessage.error(`数据验证失败：${validation.errors.join(", ")}`);
      return false;
    }

    updatingRecover.value = true;

    try {
      const result = await sheddingStore.updateSheddingLevel(
        cpu,
        SheddingType.RECOVER,
        valueToUpdate
      );

      if (result.status) {
        ElMessage.success("恢复负荷层级更新成功");
        syncLocalValues();
        return true;
      } else {
        ElMessage.error("恢复负荷层级更新失败");
        return false;
      }
    } catch (error: any) {
      handleError(error, "更新恢复负荷层级");
      return false;
    } finally {
      updatingRecover.value = false;
    }
  };

  /**
   * 重置本地值
   */
  const resetLocalValues = () => {
    syncLocalValues();
  };

  /**
   * 验证切负荷层级值
   * @param value 层级值
   */
  const validateSheddingValue = (value?: number) => {
    const valueToValidate = value !== undefined ? value : localSheddingValue.value;
    return sheddingStore.validateSheddingValue(valueToValidate);
  };

  /**
   * 验证恢复负荷层级值
   * @param value 层级值
   */
  const validateRecoverValue = (value?: number) => {
    const valueToValidate = value !== undefined ? value : localRecoverValue.value;
    return sheddingStore.validateRecoverValue(valueToValidate);
  };

  /**
   * 设置本地切负荷层级值
   * @param value 层级值
   */
  const setLocalSheddingValue = (value: number) => {
    const validation = validateSheddingValue(value);
    if (validation.isValid) {
      localSheddingValue.value = value;
    } else {
      ElMessage.warning(`切负荷层级值无效：${validation.errors.join(", ")}`);
    }
  };

  /**
   * 设置本地恢复负荷层级值
   * @param value 层级值
   */
  const setLocalRecoverValue = (value: number) => {
    const validation = validateRecoverValue(value);
    if (validation.isValid) {
      localRecoverValue.value = value;
    } else {
      ElMessage.warning(`恢复负荷层级值无效：${validation.errors.join(", ")}`);
    }
  };

  /**
   * 初始化稳控切负荷
   * @param cpu CPU 编号
   */
  const initShedding = async (cpu: number = 1) => {
    if (sheddingStore.isReady) {
      syncLocalValues();
      return;
    }

    try {
      await refreshSheddingInfo(cpu);
    } catch (error: any) {
      handleError(error, "初始化稳控切负荷");
    }
  };

  return {
    // 状态
    localSheddingValue,
    localRecoverValue,
    isReady,
    sheddingInfo,
    isLoading,
    isUpdating,
    updatingShedding,
    updatingRecover,

    // 方法
    refreshSheddingInfo,
    updateSheddingLevel,
    updateRecoverLevel,
    resetLocalValues,
    validateSheddingValue,
    validateRecoverValue,
    setLocalSheddingValue,
    setLocalRecoverValue,
    initShedding,
  };
}
